import wepy from 'wepy';
import tip from '@/utils/tip';
import { isPhone } from '@/utils/utils';
import common from '@/api/common';

/**
 * 获取验证码方法
 */
export default class CodeMixin extends wepy.mixin {
  data = {
    phone: '',
    countDown: 60,
    codeState: false
  }
  methods = {
    // 获取验证码
    async getCode(e) {
      if(isPhone(this.phone)) {
        let res = await common.getMsg({
          data: {
            phone: this.phone,
            type: e.currentTarget.dataset.type
          }
        })
        if(res.code == 2) {
          this.codeState = true;
          tip.success('验证码已发送，请注意查收!')
        }else {
          tip.error(res.msg)
        }
      }
      this.$apply();
    },
    // 获取手机号
    getPhone(e) {
      this.phone = e.detail.value;
    }
  }
  watch = {
    codeState (newValue) {
      // 倒计时
      if(newValue) {
        let date = this.countDown;
        let time = null;
        time = setInterval(() => {
          this.countDown --;
          this.$apply();
          if(this.countDown == 0) {
            clearInterval(time);
            this.countDown = date;
            this.codeState = false;
            this.$apply();
          }
        }, 1000)
      }
    }
  }
}
